//
//  BJPlayVideoViewController.m
//  BowJoy
//
//  Created by  on 2024/5/23.
//

#import "BJPlayVideoViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "NSTimer+Ch_helper.h"

@interface BJPlayVideoViewController ()
@property (nonatomic) AVPlayer *player;
@property(nonatomic, strong) id timeobserver;

@property (nonatomic) AVPlayerItem *playerItem;
@property (nonatomic) AVPlayerLayer *playerLayer;
@property (nonatomic)  UIView*playBgView;

@property (nonatomic)  UIButton*playBtn;
@property (weak, nonatomic) IBOutlet UIView *bgGroundView;

@property (nonatomic,assign)BOOL isPlay;
@property (weak, nonatomic) IBOutlet UILabel *follewNumL;

@property (weak, nonatomic) IBOutlet UILabel *titileL;
@property (weak, nonatomic) IBOutlet UILabel *contentL;
@property (weak, nonatomic) IBOutlet UIImageView *followIcon;
@property (nonatomic, assign) BOOL tapShow;//点击显示 ？隐藏
@property (nonatomic, strong) NSTimer *timer;//定时器 -- 5 秒后隐藏 头部/底部视图
@property (nonatomic, assign) NSInteger timerNub;//定时器计数

@end

@implementation BJPlayVideoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.isPlay = YES;
    //读取本地视频路径
//    NSString *path = [[NSBundle mainBundle] pathForResource:self.model.playurl ofType:@"mp4"];
     //为即将播放的视频内容进行建模
    AVPlayerItem *avplayerItem = [[AVPlayerItem alloc] initWithURL:[NSURL URLWithString:self.model.playurl]];
    self.playerItem = avplayerItem;
 //创建监听（这是一种KOV的监听模式）
    [avplayerItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
     //给播放器赋值要播放的对象模型
     AVPlayer *avplayer = [AVPlayer playerWithPlayerItem:avplayerItem];
    self.player= avplayer;
 //指定显示的Layer

    self.playerLayer = [AVPlayerLayer playerLayerWithPlayer:avplayer];
    self.playerLayer.frame = CGRectMake(0, 0, kScreenW, kScreenH);
    self.playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    [self.bgGroundView.layer addSublayer:self.playerLayer];
    [self.player play];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moviePlayDidEnd:) name:AVPlayerItemDidPlayToEndTimeNotification object:self.player.currentItem];

    
    self.playBgView = [[UIView alloc]init];
    self.playBgView.backgroundColor = [UIColor colorWithHexString:@"#000000" alpha:0.2];
    self.playBgView.layer.masksToBounds = YES;
    self.playBgView.layer.cornerRadius = 25;
    [self.view addSubview:self.playBgView];
    self.playBgView.makeCons(^{
        make.center.view(self.view);
        make.width.constants(50);
        make.height.constants(50);
    });
    
    UIButton *button = [[UIButton alloc]init];
    [button addTarget:self action:@selector(startAnimation) forControlEvents:UIControlEventTouchUpInside];
    [button setImage:[UIImage imageNamed:@"CHPlayer_pause"] forState:UIControlStateNormal];
    [self.playBgView addSubview:button];
    self.playBtn = button;
    button.makeCons(^{
        make.center.view(self.playBgView);
        make.width.constants(40);
        make.height.constants(40);
    });

    self.titileL.text = self.model.title;
    self.contentL.text = self.model.content;
    self.followIcon.image = self.model.isLike ? [UIImage imageNamed:@"icon_love_red"]:[UIImage imageNamed:@"icon_love_gray"];
    self.follewNumL.text = [NSString stringWithFormat:@"%ld",self.model.followNum];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
    [self.view addGestureRecognizer:tap];
    self.playBgView.alpha = 1;
    [self repeatsTimer];
  
}
- (void)repeatsTimer{
     [self removeRepeatsTimer];
    kWeakSelf(weakSelf);
     self.timer = [NSTimer ch_scheduledTimerWithTimeInterval:1.0f block:^{
         weakSelf.timerNub++;
          if (weakSelf.timerNub == 3) {
               [weakSelf manualHideView];
          }
     } repeats:YES];
}
- (void)removeRepeatsTimer{
     if (self.timer) {
          [self.timer invalidate];
          self.timer = nil;
          self.timerNub = 0;
     }
}

- (void)manualHideView{
     
     [self hideView];
     self.tapShow = YES;
     [self removeRepeatsTimer];
}

- (void)tapAction:(UIGestureRecognizer *)sender{
    self.tapShow?[self showView]:[self hideView];
    self.tapShow = !self.tapShow;

}
- (void)showView{
    [UIView animateWithDuration:0.35f animations:^{
        self.playBgView.alpha = 1;
    }];
}
- (void)hideView{
    [UIView animateWithDuration:0.35f animations:^{
        self.playBgView.alpha = 0;
    }];
}
- (IBAction)clickFollewBtn:(id)sender {
    if (!self.model.isLike) {
        self.model.isLike = YES;
        self.model.followNum ++;
        self.followIcon.image = self.model.isLike ? [UIImage imageNamed:@"icon_love_red"]:[UIImage imageNamed:@"icon_love_gray"];
        self.follewNumL.text = [NSString stringWithFormat:@"%ld",self.model.followNum];

    }else{
        self.model.isLike = NO;
        self.model.followNum --;
        self.followIcon.image = self.model.isLike ? [UIImage imageNamed:@"icon_love_red"]:[UIImage imageNamed:@"icon_love_gray"];
        self.follewNumL.text = [NSString stringWithFormat:@"%ld",self.model.followNum];
    }
    [[BJFMDBVoiceManager sharedManager] uptadeDataWithLike:self.model.isLike andUserId:self.model.userId];
    [[BJFMDBVoiceManager sharedManager] uptadeDataWithFollowNum:self.model.followNum andUserId:self.model.userId];


}

-(void)startAnimation{
    if (self.isPlay) {
        [self.player pause];
        [self.playBtn setImage:[UIImage imageNamed:@"CHPlayer_play"] forState:UIControlStateNormal];

    }else{
        [self.player play];
        [self.playBtn setImage:[UIImage imageNamed:@"CHPlayer_pause"] forState:UIControlStateNormal];
    }
    [self repeatsTimer];

    self.isPlay = !self.isPlay;

}
// 视频循环播放

- (void)moviePlayDidEnd:(NSNotification*)notification{

AVPlayerItem*item = [notification object];

[item seekToTime:kCMTimeZero];

[self.player play];

}

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
    
}
- (void)dealloc
{
    [self removeRepeatsTimer];
    [[NSNotificationCenter defaultCenter] removeObserver:self];

}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
